// pages/lawhall/index.js
const app = getApp()
const {
  storeset,
  storetop,
  pay,
  storeApply,
  storeedit
} = require('../../utils/api')
const {
  formatDate
} = require('../../utils/util')
const dateTimePicker = require('../../utils/dateTimePicker.js');

const {
  fetch,
  newFetch,
  hasSensitiveWords,
  replaceAll
} = require('../../utils/fetch')
const {
  BASEURL
} = require('../../utils/baseurl')
// import {Base} from '../../utils/base.js';
// var base=new Base();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: '',
    storetype_id: 0,
    name: '',
    // time: '',
    yingyetime: '',
    address: '',
    theContact: '',
    phone: '',
    idCard: '',
    theBusinessLicense: '',
    introduce: '',
    toptimes: '',
    topInfo: [],
    store_img: [],
    logo: [],
    yyzz_img: [],
    sel_start_time: '',
    sel_top_idx: -1,
    cur_mid: 0,
    region: ['请选择地区', '', ''],
    timepicker: {
      starttime: '00:00',
      endtime: '00:00'
    },
    licenselist: [], //营业执照
    licenseimgs: [],
    merlogolist: [], //商户logo
    merlogoimgs: [],
    atlaslist: [], //商户图集
    atlasimgs: [],


    checked: true,
    checked1: true,
    startimedate: formatDate(new Date()),
    freindex: 0,
    topInfo: Array,
    timeArr: ['七天', '半个月', '一个月', '一季度', '半年', '一年'],
    currentDate: new Date().getTime(),
    show: false,
    // type_id:0,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      }
      return value
    },

    dateTime1: null,
    dateTimeArray1: null,
    startYear: 2000,
    endYear: 2050,

    editval: {}, //编辑
    editid: 0, //编辑id
    ispageEdit: true,
    placetop_time: '00:00',


    typeindex: null,
    formId: '',

    customItem: '全部',
    specificarea: null,
    systemInfo: '',
    isagent: 0,
    pubdisabled:false,
    savedisabled:false,

    show_tip: 0,
    tip: 'init',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (wx.getStorageSync('specificarea')) {
      this.setData({
        specificarea: wx.getStorageSync('specificarea')
      })
    }
    if (options.index) {
      this.setData({
        type: app.globalData.merchantsTypeList[options.index].text,
        storetype_id: app.globalData.merchantsTypeList[options.index].id,
        typeindex: options.index,
        merlogolist: [app.globalData.merchantsTypeList[options.index].typeimg],
        merlogoimgs: [app.globalData.merchantsTypeList[options.index].typeimg]
      })
    }

    if (wx.getStorageSync('userInfo')) {
      let userInfo = wx.getStorageSync('userInfo');
      if (userInfo.isagent == null) {
        this.setData({
          isagent: 0
        })
      } else {
        this.setData({
          isagent: userInfo.isagent
        })
      }
      if (this.data.isagent == 0) {
        this.setData({
          phone: userInfo.mobile,
          theContact: userInfo.nickname
        })
      }
    }
    if (wx.getStorageSync('currentAddress')) {
      let addressval = wx.getStorageSync('currentAddress').address_component;
      let rgaddress = [addressval.city, addressval.province, addressval.district]
      this.setData({
        region: rgaddress
      })
    }

    fetch(`wx/store/${this.data.specificarea}/storeset`, 'POST').then(res => {
      this.setData({
        toptimes: res.toptimes
      })
    })

    fetch(`wx/store/${this.data.specificarea}/storetop`, 'POST').then(res => {
      this.setData({
        topInfo: res
      })
    })

    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
      dateTime1: obj1.dateTime,
      dateTimeArray1: obj1.dateTimeArray
    });


    console.log(options.ediddata)
    
    console.log(options.details, '上来看对方接收到了开发')

    if (options.ediddata) {
      var editdetails
      if (options.details) {
        editdetails = decodeURIComponent(options.details)
      }
      var details = editdetails && editdetails.split('&nbsp;').join('\n')
      this.setData({
        editval: options.ediddata && JSON.parse(options.ediddata),
        ispageEdit: false,
        checked:false
      })
      let {
        editval
      } = this.data;
      var imgsdata = editval.store_img && editval.store_img.split(",");
      if (editval.city) {
        var editcity = (editval.city && editval.city.split(",")) || this.data.region;
      }
      var startshi = editval.yingye_time && editval.yingye_time.split("-");
      var staradtime = editval.startTime && editval.startTime.substr(editval.startTime.length - 5)
      this.setData({
        type: editval.storetype && editval.storetype.title,
        storetype_id: editval.storetype && editval.storetype.id,
        name: editval.store_name,
        timepicker: {
          starttime: (startshi && startshi[0]) || '00:00',
          endtime: (startshi && startshi[1]) || '00:00'
        },
        yingyetime: editval.yingye_time,
        region: editcity,
        address: editval.address,
        theContact: editval.pushName,
        phone: editval.store_tel,
        idCard: editval.sfz_img,
        theBusinessLicense: editval.yyzz_code,
        merlogolist: [editval.logo],
        merlogoimgs: [editval.logo],
        licenselist: [editval.yyzz_img], //营业执照
        licenseimgs: [editval.yyzz_img],
        // introduce: editval.details,

        introduce: details,
        atlaslist: imgsdata || [], //商户图集
        atlasimgs: imgsdata || [],

        // freindex:editval.day-1
        startimedate: editval.startTime || this.data.startimedate,
        // freindex:editval.day==0? 0:editval.day-1,
        placetop_time: staradtime,
      })
    }
    if (options.editid) {
      this.setData({
        editid: options.editid
      })
    }


    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.system.indexOf('iOS') == 0) {
          that.setData({
            systemInfo: 'iOS'
          })
        } else {
          that.setData({
            systemInfo: 'Android'
          })
        }
      }
    })
  },

  bindTimeChange: function (e) {
    this.setData({
      yinyetime: e.detail.value
    })
  },




  // 是否置顶
  onChange(event) {
    this.setData({
      checked: event.detail
    })
  },
  onChange1(event) {
    this.setData({
      checked1: event.detail
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      freindex: e.detail.value
    })
  },
  onInput(event) {
  },
  togglePicker() {
    this.setData({
      show: !this.data.show
    })
  },

  jumpToAgreement() {
    wx.navigateTo({
      url: '/pages/login/agreement'
    })
  },




  //   选择时间
  bind_timepicker: function (e) {
    this.setData({
      timepicker: {
        starttime: e.detail.picker_time,
        endtime: '00:00'
      }
    })
  },
  bind_endpicker: function (e) {
    if (this.data.timepicker.starttime >= e.detail.picker_time) {
      wx.showToast({
        title: '结束时间不能小于开始时间',
        icon: 'none',
        duration: 1000
      })
      this.setData({
        timepicker: {
          starttime: this.data.timepicker.starttime,
          endtime: '00:00'
        }
      })
      return;
    }
    this.setData({
      timepicker: {
        starttime: this.data.timepicker.starttime,
        endtime: e.detail.picker_time
      },
      yingyetime: this.data.timepicker.starttime + '-' + e.detail.picker_time,
    })
  },


  // 地址选择
  bindRegionChange: function (e) {
    var val_arr = e.detail.value;
    if (val_arr[0] == '全部' && val_arr[1] == '全部' && val_arr[2] == '全部') {
      this.setData({
        region: ['请选择地区']
      })
      return;
    }
    this.setData({
      region: e.detail.value
    })

  },

  // 商家名称
  bussnessinput: function (e, type) {
    this.setData({
      name: e.detail.value
    })
  },
  // 详细地址
  adressinput: function (e, type) {
    this.setData({
      address: e.detail.value
    })
  },
  // 联系人
  thecontactinput: function (e, type) {
    this.setData({
      theContact: e.detail.value
    })
  },
  // 联系电话
  phoneinput: function (e, type) {
    this.setData({
      phone: e.detail.value
    })
  },
  // 身份证
  cardinput: function (e, type) {
    this.setData({
      idCard: e.detail.value
    })
  },

  // 营业执照编码
  licenceinput: function (e, type) {
    this.setData({
      theBusinessLicense: e.detail.value
    })
  },
  // 商户介绍
  goinputdetail: function (e) {
    this.setData({
      introduce: e.detail.value
    })
  },
  goinputCopy: function () {
    wx.setClipboardData({
      data: this.data.introduce,
      success: function (res) {
        // 添加下面的代码可以复写复制成功默认提示文本`内容已复制` 
        wx.showToast({
          title: '复制成功',
          duration: 3000
        })
        wx.getClipboardData({
          success: function (res) {}
        })
      }
    })
  },

  changeDateTime1(e) {
    let month = e.detail.value[1] + 1;
    let dtime = e.detail.value[2] + 1;
    let atime = '20' + e.detail.value[0] + '-' + month + '-' + dtime + ' ' + e.detail.value[3] + ':' + e.detail.value[4];
    this.setData({
      startimedate: atime
    })
  },
  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1,
      dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr
    });
  },

  // 置顶时间
  bindplacetopChange: function (e) {
    this.setData({
      placetop_time: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  inputFn: function (data) {
    let {
      dataName,
      value
    } = data.detail
    this.setData({
      [dataName]: value
    })
  },
  showToast: function (title) {
    wx.showToast({
      title,
      icon: 'none',
      duration: 1000
    })
  },
  bind_yyzz_img: function (e) {
    this.data.yyzz_img = e.detail.imagsetentlogs;
  },
  bind_logo: function (e) {
    this.data.logo = e.detail.imagsetentlogs;
  },
  bind_store_img: function (e) {
    this.data.store_img = e.detail.imagsetentlogs;
  },






  // 上传logo图片
  upload(e) {
    const _this = this
    var imgtype = e.currentTarget.dataset.imgtype;
    let {
      licenselist,
      merlogolist,
      atlaslist,
      atlasimgs
    } = this.data;
    var imgcount = 1;
    var resupimg = []
    if (imgtype == 'atlas') {
      // imgcount=9 - atlaslist.length
      imgcount = 9 - atlasimgs.length
    }
    wx.chooseImage({
      count: imgcount,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        var tempFilePaths = res.tempFilePaths;
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgtype == 'license') {
            licenselist.push(tempFilePaths[i]);
            this.setData({
              licenselist: licenselist,
            })
            wx.uploadFile({
              url: `${BASEURL}wx/upload/image`,
              filePath: res.tempFilePaths[i],
              name: 'image',
              formData: {},
              success: (res) => {
                if (res.statusCode == 200) {
                  var resdata = JSON.parse(res.data);
                  _this.setData({
                    // licenseimgs:_this.data.licenseimgs.concat(resdata.data.url),
                    licenseimgs: [resdata.data.url],

                  })
                }
              },
              fail: function (res) {}
            })
          }
          if (imgtype == 'logo') {
            merlogolist.push(tempFilePaths[i]);

            this.setData({
              merlogolist: merlogolist,
            })
            wx.uploadFile({
              url: `${BASEURL}wx/upload/image`,
              filePath: res.tempFilePaths[i],
              name: 'image',
              formData: {},
              success: (res) => {
                if (res.statusCode == 200) {
                  var resdata = JSON.parse(res.data);
                  this.setData({
                    // merlogoimgs:_this.data.merlogoimgs.concat(resdata.data.url),
                    merlogoimgs: [resdata.data.url],
                  })
                }
              },
              fail: function (res) {}
            })
          }
        }
        // 商户图集  九图
        if (imgtype == 'atlas') {
          _this.setData({
            tip: '已选图片,正在上传..',
            show_tip: 1,
          })
          res.tempFilePaths.forEach((item, index) => {
            wx.uploadFile({
              url: `${BASEURL}wx/upload/image`,
              filePath: item,
              name: 'image',
              formData: {
                type: 'img'
              },
              success: (res) => {
                var resdata = JSON.parse(res.data);
                if (resdata.code == '200') {
                  resupimg[index] = resdata.data.url
                  this.setData({
                    atlasimgs: resupimg
                  })
                  _this.setData({
                    tip: '显示',
                    show_tip: 0
                  })
                } else if (resdata.code == '404') {
                  wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                  })
                }
              },
              fail: function (res) {
                console.log(res, 'fail')
              }
            })
          })
        }
      }
    })
  },
  previewImage(e) {
    let index = e.target.dataset.index
    let {
      licenselist,
      merlogolist,
      atlaslist
    } = this.data;
    var imgtype = e.currentTarget.dataset.imgtype;
    if (imgtype == 'license') {
      wx.previewImage({
        current: licenselist[index],
        urls: licenselist
      })
    }
    if (imgtype == 'logo') {
      wx.previewImage({
        current: merlogolist[index],
        urls: merlogolist
      })
    }
    if (imgtype == 'atlas') {
      wx.previewImage({
        // current: atlaslist[index],
        // urls: atlaslist
        current: atlasimgs[index],
        urls: atlasimgs
      })
    }
  },
  remove(e) {
    const _this = this
    let index = e.target.dataset.index
    let {
      licenselist,
      merlogolist,
      atlaslist,
      licenseimgs,
      merlogoimgs,
      atlasimgs
    } = this.data;
    var imgtype = e.currentTarget.dataset.imgtype;
    if (imgtype == 'license') {
      wx.showModal({
        title: '提示',
        content: '您确定要删除本张图片吗？',
        success(res) {
          if (res.confirm) {
            licenselist.splice(index, 1)
            licenseimgs.splice(index, 1)
            _this.setData({
              licenselist,
              licenseimgs
            })
          } else if (res.cancel) {}
        }
      })
    }
    if (imgtype == 'logo') {
      wx.showModal({
        title: '提示',
        content: '您确定要删除本张图片吗？',
        success(res) {
          if (res.confirm) {
            merlogolist.splice(index, 1)
            merlogoimgs.splice(index, 1)
            _this.setData({
              merlogolist,
              merlogoimgs
            })
          } else if (res.cancel) {}
        }
      })
    }
    if (imgtype == 'atlas') {
      wx.showModal({
        title: '提示',
        content: '您确定要删除本张图片吗？',
        success(res) {
          if (res.confirm) {
            // atlaslist.splice(index, 1)
            atlasimgs.splice(index, 1)
            _this.setData({
              // atlaslist,
              atlasimgs
            })
          } else if (res.cancel) {}
        }
      })
    }
  },



  // 置顶
  publishFN: function (e) {
    this.setData({
      formId: e.detail.formId
    })
    if (this.data.checked == false) {
      this.data.sel_top_idx = -1;
    } else {
      this.data.sel_top_idx = 0;
    }
    // this.data.sel_start_time = this.data.sel_start_time;
    let data = this.data
    // else if (!data.address) {
    //     this.showToast('请填写正确地址');
    //     return;
    // }
    if (!data.name) {
      this.showToast('请填写商户名称');
      return;
    }
    var newtitle = hasSensitiveWords(data.name);
    if (newtitle) {
      wx.showToast({
        title: '标题包含敏感词，已经自动处理为*，请重新编辑',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        name: replaceAll(data.name, newtitle),
      });
      return;
    }

    if (data.name.indexOf('*') == 0) {
      this.showToast('请填写正确的商户名称');
      return;
    }

    var newintroduce = hasSensitiveWords(data.introduce)
    if (newintroduce) {
      wx.showToast({
        title: '商户介绍包含敏感词，已经自动处理为*，请重新编辑',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        introduce: replaceAll(data.introduce, newintroduce),
      });
      return;
    }

    if (this.data.introduce.indexOf('*') == 0) {
      this.showToast('请填写正确的商户介绍');
      return;
    }

    wx.showLoading({
      title: '发布中',
    })
   this.setData({
    pubdisabled:true
   })

    let userInfo = wx.getStorageSync('userInfo');

    var that = this;

    var re_param = {
      "area": this.data.specificarea,
      "store_name": that.data.name,
      "memberId": userInfo["id"],
      "pushName": that.data.theContact,
      "store_tel": that.data.phone,
      "city": that.data.region,
      "address": that.data.address,
      "yyzz_img": that.data.licenseimgs.join(","),
      "yyzz_code": that.data.theBusinessLicense,
      "sfz_img": that.data.idCard,
      "storetype_id": that.data.storetype_id,
      "logo": that.data.merlogoimgs.join(","),
      "store_img": that.data.atlasimgs.join(","),
      "details": that.data.introduce  && that.data.introduce.split('\n').join('&nbsp;'),
      "yingye_time": that.data.yingyetime,
      "istop": 0,
      "startTime": "",
      "day": 0,
      "deadline": 0,
      "fee": 0
    }
    //选择置顶
    if (this.data.sel_top_idx >= 0) {
      var sel_top_info = this.data.topInfo[this.data.freindex];
      re_param["istop"] = 1;
      re_param["startTime"] = this.data.startimedate;
      re_param["day"] = sel_top_info['day'];
      re_param["deadline"] = this.data.toptimes;
      re_param["fee"] = sel_top_info['curmoney'];
    }

    if (this.data.typeindex) {
      fetch(`wx/store/${this.data.specificarea}/apply`, 'POST', re_param).then(res => {
        if (res) {
          that.data.cur_mid = res.id;
          if (res.istop == 1 && res.fee > 0) {
            wx.hideLoading()
            if (that.data.systemInfo == 'iOS') {
              wx.showToast({
                title: 'iOS不支持虚拟支付',
                icon: 'none',
                duration: 1500
              })
              return;
            }
            that.pay(res.fee, res.id, res.orderId);
          } else {
            //跳转
            that.endjump();
          }
        }
      })
    }

    //  判断是否是编辑页面
    if (this.data.editval) {
      if (this.data.editid) {
        re_param['id'] = this.data.editid
        re_param['adStartTime'] = this.data.placetop_time
        this.setData({
          savedisabled:true
        })

        if (this.data.checked) {
          wx.hideLoading()
          if (that.data.systemInfo == 'iOS') {
            wx.showToast({
              title: 'iOS不支持虚拟支付',
              icon: 'none',
              duration: 1500
            })
            return;
          }
          that.payRenew(this.data.editid, re_param)
        }  else {
          newFetch(`wx/store/${this.data.specificarea}/edit`, 'POST', re_param).then(res=>{
            if(res) {
                wx.hideLoading()
                that.endjump();
            }
          })
        }
      }
    }
  },
  pay: function (fee, typeId, orderId) {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let obg = {
      area: this.data.specificarea,
      openId: userInfo['openid'],
      memberId: userInfo['id'],
      // money: '0.01',
      money: this.data.topInfo[this.data.freindex]['curmoney'],
      orderdesc: '小微服务',
      orderId: orderId, // new Date().getTime() + '',
      type: 2,
      typeId: typeId,
      formId: that.data.formId
    }
    fetch(`wx/pay/${this.data.specificarea}/pay`, 'POST', obg).then(info => {

      wx.requestPayment({
        timeStamp: info.timeStamp,
        nonceStr: info.nonceStr,
        package: `prepay_id=${info.prepayId}`,
        signType: 'MD5',
        paySign: info.paySign,
        success: function (res) {
          wx.showToast({
            title: '付款成功',
            icon: 'success',
            duration: 2000
          })
          setTimeout(() => {
            //跳转
            that.endjump();
          }, 2000)
        },
        fail: function (res) {
          that.setData({
            pubdisabled:false
          })
          wx.showToast({
            title: '取消付款成功',
            icon: 'success',
            duration: 2000
          })
        }
      })
    })
  },
  endjump: function () {
    var that = this;
    setTimeout(() => {
      wx.redirectTo({
        url: '/pages/showmsg/index?id=' + 'merchants',
      })
    }, 3000)
  },

  
  payRenew: function (typeId, re_param) {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let obg = {
      area: this.data.specificarea,
      openId: userInfo['openid'],
      memberId: userInfo['id'],
      // money: '0.01',
      money: this.data.topInfo[this.data.freindex]['curmoney'],
      orderdesc: '小微服务',
      // orderId: orderId,
      type: 1,
      typeId: typeId,
      formId: that.data.formId
      // type就是那个消息1，商户2 广告3 typeid就是对应的id
    }
    fetch(`wx/pay/${this.data.specificarea}/payRenew`, 'POST', obg).then(info => {
      wx.requestPayment({
        timeStamp: info.timeStamp,
        nonceStr: info.nonceStr,
        package: `prepay_id=${info.prepayId}`,
        signType: 'MD5',
        paySign: info.paySign,
        success: function (res) {
          wx.showToast({
            title: '付款成功',
            icon: 'success',
            duration: 2000
          })
          that.saveEdit(info, re_param)
          // that.endjump();
        },
        fail: function (res) {
          that.setData({
            savedisabled: false
          })
          wx.showToast({
            title: '取消付款成功',
            icon: 'success',
            duration: 2000
          })
        }
      })
    })
  },

  saveEdit:function (info, re_param) {
    var that = this;
    if (info.orderCode) {
      newFetch(`wx/pay/${this.data.specificarea}/checkOrderPayStatus`, 'POST', {
        orderId: info.orderCode
      }).then(res => {
        if (res.data.payStatus == 1) {
          re_param['payStatus'] = res.data.payStatus
          re_param['orderCode'] = res.data.orderCode
          newFetch(`wx/store/${this.data.specificarea}/edit`, 'POST', re_param).then(res=>{
            if(res) {
                wx.hideLoading()
                that.endjump();
            }
          })
        }
      })
    }
  },

  bind_cellcity: function (e) {
    this.data.region = this.data.region;
  },
  bind_startAddress: function (e) {
    this.data.startAddress = e.detail.region;
  },
  bind_endAddress: function (e) {
    this.data.endAddress = e.detail.region;
  },


})